package com.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: mayu
 * @date: 2021年04月09日 11:36
 */
public class TestNotifyHoldingLock {
    //volatile List lists = new ArrayList<>();
    volatile List lists = Collections.synchronizedList(new ArrayList<>());

    void add(Object o) {
        lists.add(o);
    }

    int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        TestNotifyHoldingLock tnhl = new TestNotifyHoldingLock();

        final Object lock = new Object();

        //t2相当于监视线程
        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t2启动");
                if (tnhl.lists.size() != 5) {
                    try {
                        //wait会释放锁
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2结束");
            }
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t1启动");
                for (int i = 0; i < 10; i++) {
                    tnhl.add(i);
                    System.out.println(i);
                    if (tnhl.lists.size() == 5) {
                        //notify不会释放锁
                        lock.notify();
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t1结束");
            }
        }, "t1").start();

    }
}
